function setupJSBridge(callback) {
    if (window.WebViewJavascriptBridge) {
        return callback(window.WebViewJavascriptBridge);
    } else if (window.isClient && window.isAndroid) {
        document.addEventListener(
            'WebViewJavascriptBridgeReady',
            () => {
                callback(window.WebViewJavascriptBridge);
            },
            false
        );
    } else if (window.isClient && window.isIOS) {
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        const WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'https://__bridge_loaded__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(() => {
            document.documentElement.removeChild(WVJBIframe);
        }, 0);
    } else {
        // console.warn( 'JSBridge: WebViewJavascriptBridge undefined.' );
        // throw new Error( 'JSBridge: WebViewJavascriptBridge undefined.' );
        return callback(null);
    }
}

const JSBridge = {
    init() {
        const ua = navigator.userAgent;
        const apps = {
            SSCM: '上上参谋',
            CYKD: '创业开店',
            TDY: '拓店云'
        };
        for (const appId in apps) {
            if (ua.indexOf(appId) !== -1) {
                window.isClient = true;
                window._appId = appId;
                window._appName = apps[appId];
                break;
            }
        }
        window.isAndroid = ua.indexOf('Android') !== -1;
        window.isIOS = ua.indexOf('iPhone') !== -1 || ua.indexOf('iPad') !== -1;
        window.isIPX = false;
        // 小程序
        window.isWX = window['__wxjs_environment'] === 'miniprogram'; /* || ua.indexOf( 'MicroMessenger' ) > - 1 */
        // 微信
        window.isWeChat = ua.toLowerCase().match(/MicroMessenger/i) == 'micromessenger';
        if (window.isIOS) {
            // XR
            if (window.devicePixelRatio === 2 && window.screen.width === 414 && window.screen.height === 896) {
                window.isIPX = true;
            } else if (window.devicePixelRatio === 3) {
                // X, XS
                if (window.screen.width === 375 && window.screen.height === 812) {
                    window.isIPX = true;
                    // XS Max
                } else if (window.screen.width === 414 && window.screen.height === 896) {
                    window.isIPX = true;
                    // 12, Pro
                } else if (window.screen.width === 390 && window.screen.height === 844) {
                    window.isIPX = true;
                    // 12 Mini
                } else if (window.screen.width === 360 && window.screen.height === 780) {
                    window.isIPX = true;
                    // 12 Max
                } else if (window.screen.width === 428 && window.screen.height === 926) {
                    window.isIPX = true;
                }
            }
        }
        if (window.isClient) {
            console.log(`SSCM client ${window.isAndroid ? 'Android' : 'iOS'}, version: ${ua.substr(ua.indexOf('SSCM') + 5)}`);
        }
        setupJSBridge((bridge) => {
            // 安卓需要进行一次写入
            if (window.isAndroid && bridge) {
                bridge.init((message, responseCallback) => {
                    responseCallback({ Hi: 'SSCM' });
                });
            }
        });
    },
    appName() {
        return window._appName || '拓店云';
    },
    callHandler(method, data, callback) {
        // Methods validate
        // TODO
        setupJSBridge((bridge) => {
            if (bridge) {
                bridge.callHandler(method, data, callback);
            } else if (typeof callback === 'function') {
                callback(null);
            }
        });
    },
    check(code) {
        return code === window._appCode;
    },
    registerHandler(method, callback) {
        // Methods validate
        // TODO
        setupJSBridge((bridge) => {
            if (bridge) {
                bridge.registerHandler(method, (data, responseCallback) => {
                    callback(data, responseCallback);
                });
            }
        });
    },
    report(id, data) {
        // Get Source Data
        // TODO
        const template = {
            event_time: '',
            ref_id: '',
            ref_name: '',
            ref_type: '', // 业务类型 文章: ARTICLE 前置报告: PRE_REPORT 报告表单: FORM_REPORT 关键字搜索：SEARCH,
            source_ref_id: '', // 来源业务id,
            source_ref_name: '', // 来源业务名称,
            source_ref_type: '' // 来源业务类型 如以上业务为文章浏览，那么文章浏览来源首页、发现、搜索
        };
        setupJSBridge((bridge) => {
            if (bridge) {
                bridge.callHandler('onEventObject', {
                    event_id: id,
                    map: data && typeof data === 'object' ? Object.assign(template, data) : template
                });
            }
        });
    },
    BPR(id, pid, data) {
        setupJSBridge((bridge) => {
            if (bridge) {
                if (data && typeof data !== 'string') data = JSON.stringify(data);
                bridge.callHandler('onEventReport', {
                    pageId: id || '00000',
                    refId: pid || null,
                    extra: !data || data === '{}' ? null : data
                });
                console.log(`pv埋点: pageId: ${id},refId: ${pid},extra: ${!data || data === '{}' ? null : data}`);
            }
        });
    }
};

export default JSBridge;
